package lib.bone.system.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Validator;
import cn.hutool.extra.pinyin.PinyinUtil;
import lib.bone.common.constant.CommonConst;
import lib.bone.common.constant.ResponseCodeConst;
import lib.bone.common.core.domain.PageResultDTO;
import lib.bone.common.core.domain.ResponseDTO;
import lib.bone.common.core.redis.RedisCache;
import lib.bone.common.exception.BusinessException;
import lib.bone.system.constant.LoginResponseCodeConst;
import lib.bone.system.dao.SysUserDAO;
import lib.bone.system.domain.dto.LoginBody;
import lib.bone.system.domain.entity.SysUser;
import lib.bone.system.domain.vo.LoginVO;
import lib.bone.system.domain.vo.SysUserBasic;
import lib.bone.system.domain.vo.UserBaseVO;
import lib.bone.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

/**
 * @Author : Kindear
 * @Date : 2021-11-17
 */
@Slf4j
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    RedisCache redisCache;

    @Autowired
    SysUserDAO sysUserDAO;


    @Override
    public Optional<SysUser> findByUserName(String userName) {
        return sysUserDAO.findByUserName(userName);
    }

    @Override
    public SysUser saveOne(SysUser user) {
        if (Validator.isNotEmpty(user.getId())){
            throw new BusinessException(ResponseCodeConst.ERROR_PARAM);
        }
        return sysUserDAO.save(user);
    }

    @Override
    public SysUser updateOne(SysUser user) {
        if (Validator.isEmpty(user.getId())){
            throw new BusinessException(ResponseCodeConst.ERROR_PARAM);
        }
        String initial = PinyinUtil.getFirstLetter(user.getNickName(),"").substring(0,1);
        SysUser sysUser = new SysUser();
        BeanUtil.copyProperties(user,sysUser,CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
        sysUser.setInitial(initial);
        return sysUserDAO.save(sysUser);
    }

    @Override
    public List<SysUser> findByIds(List<Long> userIds) {
        return sysUserDAO.findByIdIn(userIds);
    }

    @Override
    public List<SysUser> findByUserNames(List<String> userNames) {
        return sysUserDAO.findByUserNameIn(userNames);
    }

    @Override
    public SysUserBasic buildBasic(SysUser user) {
        SysUserBasic basic = new SysUserBasic();
        BeanUtil.copyProperties(user,basic,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
       // basic.setDeptName(user.getDeptId());
        return basic;
    }

    @Override
    @Transactional
    public PageResultDTO<SysUser> getAll(Pageable pageable, Example<SysUser> example) {
        /**
         * 根据是否为空进行判断
         */
        // bug fix @ jsq
       // List<SysUser> list = sysUserDAO.findAll();
       // System.out.println(list.toString());
        Page<SysUser> sysUserPage;
        if(Validator.isEmpty(example)){
             sysUserPage = sysUserDAO.findAll(pageable);
        }
        else {
             sysUserPage = sysUserDAO.findAll(example,pageable);
        }
        /**
         * 获取分页主体内容
         */
        List<SysUser> sysUserList = sysUserPage.getContent();
        PageResultDTO<SysUser> pageResultDTO = new PageResultDTO<>();


        //封装分页请求结果
        pageResultDTO.setContent(sysUserList);
        pageResultDTO.setSize(sysUserPage.getSize());
        pageResultDTO.setTotalPages(sysUserPage.getTotalPages());
        pageResultDTO.setNumber(sysUserPage.getNumber());
        pageResultDTO.setTotalElements(sysUserPage.getTotalElements());
        return pageResultDTO;
    }

    @Override
    public ResponseDTO userLogout() {
        //Long userId = StpUtil.getLoginIdAsLong();
        StpUtil.logout();
        //@TODO 异步写入用户日志

        return ResponseDTO.succData("退出成功!");
    }

    @Override
    public Optional<SysUser> getById(Long id) {
        return sysUserDAO.findById(id);
    }
    @Override
    public ResponseDTO userLogin(LoginBody loginBody) {
        //log.info(loginBody.toString());
        Optional<SysUser> sysUserOp = sysUserDAO.findByUserName(loginBody.getUsername());
        if(sysUserOp.isPresent()){
            SysUser sysUser = sysUserOp.get();
            if(sysUser.getPassword().equals(loginBody.getPassword())){
                String captchaCode = redisCache.getCacheObject(loginBody.getUuid());
                log.info("UUID:["+loginBody.getUuid()+"]对应的验证码为:"+captchaCode);
                //清除缓存中的图片
                redisCache.deleteObject(CommonConst.CAPTCHA_CODE_KEY.concat(loginBody.getUuid()));
                if(captchaCode.equals(loginBody.getCode())){
                    log.info("验证码匹配");
                }else {
                    return ResponseDTO.wrap(LoginResponseCodeConst.LOGIN_FAILED,"验证码错误");
                }
                StpUtil.login(sysUser.getId());
                LoginVO loginVO = new LoginVO();
                BeanUtil.copyProperties(sysUser,loginVO, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
                loginVO.setToken(StpUtil.getTokenValue());
                return ResponseDTO.succData(loginVO);
            }else {
                return ResponseDTO.wrap(LoginResponseCodeConst.LOGIN_FAILED);
            }
        }else {
            return ResponseDTO.wrap(LoginResponseCodeConst.LOGIN_FAILED);
        }
    }

//    @Override
//    public ResponseDTO<SysUser> saveOne(UserAddDTO userAddDTO) {
//        SysUser sysUser = new SysUser();
//        BeanUtil.copyProperties(userAddDTO,sysUser,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
//        sysUser.setStatus(1);
//        return ResponseDTO.succData(saveOne(sysUser));
//    }

    @Override
    public ResponseDTO deleteById(Long userId) {
        sysUserDAO.deleteById(userId);
        //@TODO 需要验证与 userId 绑定的数据是否清理完全

        return ResponseDTO.succMsg("删除成功");
    }

    @Override
    public ResponseDTO resetUserPassword(Long userId,String password){
        Optional<SysUser> sysUserOp = sysUserDAO.findById(userId);
        if(!sysUserOp.isPresent())
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        if (StpUtil.getRoleList().contains("admin") || userId.equals(StpUtil.getLoginIdAsLong())){
            SysUser sysUser = sysUserOp.get();
            sysUser.setPassword(password);
            sysUserDAO.save(sysUser);
            return ResponseDTO.succMsg("重置成功!");
        }else {
            return ResponseDTO.wrap(ResponseCodeConst.UNAUTHORIZED);
        }

    }

    @Override
    public List<SysUser> findByDept(Long deptId) {
        return sysUserDAO.findByDeptId(deptId);
    }


    @Override
    public List<UserBaseVO> getAllUserBase() {
        return sysUserDAO.getAllUserBase();
    }
}
